<?php
/**
 * @description : confirm the choose plan for user
 * @author      : stephen.mo
 * @date        : 2010/09/02
 */
require_once "TVB/OAuth/common.inc.php";
#ini_set('display_errors','on');

$current_page     = OAuthConfig::PAGE_PLAN_PAYMENT;
$login_id         = (isset($_REQUEST['login_id'])) ? $_REQUEST['login_id'] : NULL;
$access_token     = (isset($_REQUEST['oauth_token'])) ? $_REQUEST['oauth_token'] : NULL;
$call_back        = (isset($_REQUEST['call_back'])) ? $_REQUEST['call_back'] : NULL;
$reback_url       = (isset($_REQUEST['reback_url'])) ? $_REQUEST['reback_url'] : NULL;
$lang             = (isset($_REQUEST['lang'])) ? OAuthUtils::chkLang($_REQUEST['lang']) : OAuthConfig::DEFAULT_SUPPORT_LANG;
$p_lang           = (isset($_REQUEST['p_lang'])) ? OAuthUtils::chkLang($_REQUEST['p_lang']) : NULL;
$pukey            = (isset($_REQUEST['pukey'])) ? $_REQUEST['pukey'] : NULL;
$pkgInfo_id       = (isset($_REQUEST['pkg_id'])) ? $_REQUEST['pkg_id'] : NULL;
$pkgInfo_version  = (isset($_REQUEST['pkg_v'])) ? $_REQUEST['pkg_v'] : NULL;
$login_id         = (!empty($login_id)) ? $login_id : OAuthUtils::getDefaultLoginId();

//get ptoken
$params = array();
$params['oauth_token'] = $access_token;
$params['lang']        = $lang;
$params['login_id']    = $login_id;
$params['call_back']   = urlencode($call_back);
$params['reback_url']  = urlencode($reback_url);
//setting path.
$base_server_path      = OAuthConfig::OAuthDomainUrl($_SERVER);
$base_back_url         = OAuthConfig::OAuthGetBackUrl($_SERVER);
$message_url           = $base_server_path.OAuthConfig::DEFAULT_SHOW_MESSAGE_URL;
$oauth_token_str       = (!empty($access_token)) ? '&oauth_token='.$access_token : NULL;
$login_id_str          = (!empty($login_id)) ? '&login_id='.$login_id : NULL;
$lang_str              = '&lang='.$lang;
$call_back_str         = (isset($call_back) && !empty($call_back)) ? '&call_back='.urlencode($call_back) : NULL;
$reback_url_str        = (isset($reback_url) && !empty($reback_url)) ? '&reback_url='.urlencode($reback_url) : NULL;
$cancel_url            = $base_server_path.OAuthConfig::DEFAULT_AJAX_URL.'?item=logout'.$call_back_str.$reback_url_str.$lang_str.$oauth_token_str;

//verify access token.
if (OAuthModelConfig::IS_NEED_CHECK_OAUTHTOKEN) {
    $ret = OAuthUtils::verifyAccessToken($access_token);
    if (!$ret || !$ret['flag']) {
        $other_msg = array('call_back'=>(isset($call_back) ? urlencode($call_back) : urlencode($reset_page_url)) );
        OAuthUtils::toMessageUrl($message_url,OAuthModelConfig::M_PAGE_OF_ERROR,OAuthModelConfig::DEFAULT_CONST_FALIURE,$lang,array(1005,1006),$other_msg);
    }
    //try to get login id from oauth token vars.
    if (empty($login_id)) {
        $user = unserialize($ret['data']['data']);
        $login_id = (!empty($user)) ? OAuthUtils::getLoginIdByEmail($user->user) : NULL;
    }
}

//check user & call_back
if (empty($login_id) || !OAuthUtils::chkIsLogin($login_id,$access_token)) {
    $tmp_base_param = '?call_back='.urlencode($call_back).'&reback_url='.urlencode($reback_url).$oauth_token_str.$login_id_str.'&lang='.$lang.
                      '&pkg_id='.$pkgInfo_id.'&pkg_v='.$pkgInfo_version.'&pukey='.$pukey;              
    $tmp_goback_url = $base_server_path.OAuthConfig::DEFAULT_INFORMATION_URL.$tmp_base_param;
    OAuthUtils::redirectTo($tmp_goback_url);
    exit;
}

//get ptoken & pukey & verify it .
$ptoken = OAuthUtils::getPToken();
if (!empty($pukey) && !empty($ptoken)) {
    $pukey = OAuthUtils::reGenPUKey($pukey,$ptoken);
}
else {
    OAuthUtils::delPToken();
    OAuthUtils::redirectTo('restart_url',$params);
}

//if login id is not empty then need to check the user can or not to buy a plan.
if (!empty($login_id)) {
    //check user can buy plan.
    $rev = OAuthUtils::chkIfUserCanBuyPlan($login_id);
    //if the user have a exists plan and this plan not expiry then show message to ask user ,his plan is still effective.
    if ((isset($rev) && $rev==1)) {
        $tmp_confirm_url = (isset($call_back)) ? $call_back : '#';
        $other_msg = array('login_id'=>$login_id,'call_back'=>urlencode($tmp_confirm_url));
        OAuthUtils::delPToken();
        OAuthUtils::toMessageUrl($message_url,OAuthModelConfig::M_PAGE_OF_PROMPT,OAuthModelConfig::DEFAULT_CONST_FALIURE,$lang,array(1031),$other_msg);
        exit;
    }
}

//setting urls.
$base_param_url   = $login_id_str.$oauth_token_str.'&lang='.$lang.'&pukey='.$pukey.'&reback_url='.urlencode($reback_url);
$jqtouch_url      = $base_server_path.OAuthModelConfig::DEFAULT_MOBILE_TEMPLATE;
$header_url       = $base_server_path.OAuthConfig::DEFAULT_HEADER_URL;
$ajax_url         = $base_server_path.OAuthConfig::DEFAULT_AJAX_URL;
$action_url       = $base_server_path.OAuthConfig::DEFAULT_CONFIRM_URL.'?call_back='.urlencode($call_back);
$restart_url      = $base_server_path.OAuthConfig::DEFAULT_CMODEL_URL.'?call_back='.urlencode($call_back).$base_param_url;

//get form data from memcache.
$fdata = array();
$tmpData = OAuthUtils::getFormData($pukey,$ptoken);
if (!$tmpData->retFlag) {
    $retry_url = OAuthConfig::OAuthGetBuyPlanFirst($params);
    $other_msg = array('call_back'=>urlencode($retry_url));
    OAuthUtils::toMessageUrl($message_url,OAuthModelConfig::M_PAGE_OF_PROMPT,OAuthModelConfig::DEFAULT_CONST_FALIURE,$lang,array(1000),$other_msg);
    exit;
}
$tmpData = $tmpData->data;
$fdata['m_login_id']     = (isset($tmpData->m_login_id)) ? $tmpData->m_login_id : $login_id;
$fdata['m_call_back']    = (isset($tmpData->m_call_back)) ? $tmpData->m_call_back : $call_back;
$fdata['m_lang']         = (isset($tmpData->m_lang)) ? $tmpData->m_lang : $lang;
$fdata['m_reback_url']   = (isset($tmpData->m_reback_url)) ? $tmpData->m_reback_url : $reback_url;
$fdata['m_model']        = (isset($tmpData->m_model)) ? $tmpData->m_model : 'TVB';
$fdata['p_plan_id']      = (isset($tmpData->p_plan_id)) ? $tmpData->p_plan_id : $pkg_id;
$fdata['p_version_id']   = (isset($tmpData->p_version_id)) ? $tmpData->p_version_id : $pkg_version;
$fdata['p_bill_address'] = (isset($tmpData->p_bill_address)) ? $tmpData->p_bill_address : '';
$fdata['p_lang']         = (isset($tmpData->p_lang)) ? $tmpData->p_lang : '';
$last_page               = (isset($tmpData->current_page)) ? $tmpData->current_page : NULL;
$back_url_top            = (isset($tmpData->m_step_back_IV)&&!empty($tmpData->m_step_back_IV)) ? $tmpData->m_step_back_IV.'&pukey='.$pukey : $base_back_url.'&pukey='.$pukey;

//check allow access pages.
$allow_pages  = array(
    OAuthConfig::PAGE_PLAN_CONFIRM,
);
if (!in_array($last_page,$allow_pages)) {
    OAuthUtils::delPToken();
    OAuthUtils::redirectTo('restart_url',$params);
}

//generate a submit form.
//$msgbox_url_pkg = $message_url_pkg.'&errids='.json_encode(array(1013));
if (empty($pkgInfo_id) || empty($pkgInfo_version)) {
    $pkgInfo_id      = $tmpData->p_plan_id;
    $pkgInfo_version = $tmpData->p_version_id;
}

//if empty pkg info then goto choose plan page.
if (empty($pkgInfo_id) || empty($pkgInfo_version) ) {
    $tmp_goback_url = '?call_back='.urlencode($call_back).'&reback_url='.$reback_url.$oauth_token_str.$login_in_str.'&lang='.$lang.'&pukey='.$pukey; 
    $retry_url = $base_server_path.OAuthConfig::DEFAULT_CHOOSE_PLAN_URL.$tmp_goback_url;
    $other_msg = array('call_back'=>urlencode($retry_url));
    OAuthUtils::toMessageUrl($message_url,OAuthModelConfig::M_PAGE_OF_PROMPT,OAuthModelConfig::DEFAULT_CONST_FALIURE,$lang,array(1013),$other_msg);
    exit;
}

//get package info type.
if (!empty($pkgInfo_id) && !empty($pkgInfo_version)) {
    $pkgInfos     = OAuthUtils::getPkgInfo($pkgInfo_id,$pkgInfo_version,$lang);
    $pkgInfo_type = (!empty($pkgInfos)) ? $pkgInfos->pkg_type : NULL;
    $is_post_page = (OAuthModelConfig::PKG_TYPE_CLP==$pkgInfo_type) ? 0 : 1;
}


//set data to memcache.
$fdata['current_page']    = $current_page;
$fdata['m_step_back_I']   = (isset($tmpData->m_step_back_I)) ? $tmpData->m_step_back_I : '';
$fdata['m_step_back_II']  = (isset($tmpData->m_step_back_II)) ? $tmpData->m_step_back_II : '';
$fdata['m_step_back_III'] = (isset($tmpData->m_step_back_III)) ? $tmpData->m_step_back_III : '';
$fdata['m_step_back_IV']  = (isset($tmpData->m_step_back_IV)) ? $tmpData->m_step_back_IV : '';
$fdata['m_step_back_V']   = $base_back_url;
$ret = OAuthUtils::setFormData($pukey,$ptoken,$fdata);
if (!$ret) {
    //not success need to retry it.
    $retry_url = OAuthConfig::OAuthGetBuyPlanFirst($params);
    $other_msg = array('call_back'=>$retry_url);
    OAuthUtils::toMessageUrl($message_url,OAuthModelConfig::M_PAGE_OF_PROMPT,OAuthModelConfig::DEFAULT_CONST_FALIURE,$lang,array(1000),$other_msg);
    exit;
}

$pkgInfo = (!isset($pkgInfo)) ? ((isset($pkgInfos)) ? (array)$pkgInfos : array()) : (array)$pkgInfo;
$agree_ment_link          = $message_url.'?act=agree&lang='.$lang.'&flag='.OAuthModelConfig::DEFAULT_CONST_SUCCESS;

//form data
$microtime                = OAuthModelConfig::getMicroFloatTime();
$langArr                  = OAuthModelConfig::$langArr;
$currencyArr              = OAuthModelConfig::$currencyArr;
$fLang                    = (!isset($lang) || empty($lang)) ? 'E' : (isset($langArr[$lang]) ? $langArr[$p_lang] : 'E');
$pkg_currcode             = isset($pkgInfo['currency_code']) ? $pkgInfo['currency_code'] : 'USD';
$currCode                 = isset($currencyArr[$pkg_currcode]) ? $currencyArr[$pkg_currcode] : '840';
// setting form datas
$paymentUrls              = OAuthModel::getInstance()->getAsiaPayUrls($_REQUEST);
$form['action']           = isset($paymentUrls['api']) ? $paymentUrls['api'] : '';

if (is_object($paymentUrls['merchantId'])) {
    $merchantIds          = (array)$paymentUrls['merchantId'];
    $hidden['merchantId'] = (isset($merchantIds[$pkg_currcode])) ? $merchantIds[$pkg_currcode] : '';
}
else {
    $hidden['merchantId'] = isset($paymentUrls['merchantId']) ? $paymentUrls['merchantId'] : '';
}

$hidden['remark']       = '';
$hidden['amount']       = $pkgInfo['price'];
$hidden['orderRef']     = '';
$hidden['currCode']     = $currCode;
$hidden['pMethod']      = '';
$hidden['cardNo']       = '';
$hidden['securityCode'] = '';
$hidden['cardHolder']   = '';
$hidden['epMonth']      = '';
$hidden['epYear']       = '';
$hidden['payType']      = 'N';
$hidden['successUrl']   = isset($paymentUrls['successUrl']) ? $paymentUrls['successUrl'].'&pukey='.$pukey : '';
$hidden['failUrl']      = isset($paymentUrls['failUrl'])    ? $paymentUrls['failUrl'].'&pukey='.$pukey    : '';
$hidden['errorUrl']     = isset($paymentUrls['errorUrl'])   ? $paymentUrls['errorUrl'].'&pukey='.$pukey   : '';
$hidden['lang']         = $fLang;
$form['hidden']         = $hidden;

//setting page info vars
$payment_page_info      = OPI::$payment_page_info;
$payment_buttons        = OPI::$payment_button_info;
//setting the form datas into array.
$using_real_env         = OAuthModelConfig::USING_TEMPLATE_ON_REAL_ENV;
$page                   = OAuthModelConfig::M_PAGE_OF_PAYMENT;
$form['lang']           = $lang;
$form['method']         = 'POST';
$form['title']          = $payment_page_info[$lang]['page_title'];
$form['payment_title']  = $payment_page_info[$lang]['payment_page_title'];
$form['ajax_url']       = $ajax_url;
$form['success_url']    = $hidden['successUrl'];
$form['restart_url']    = $restart_url;
$form['a_step']         = 'four';
$form['agree_ment_url'] = $agree_ment_link;
$form['payment_info']   = array(
                                'payment_note'=>$payment_page_info[$lang]['p_card_type'],
                                'card_owner'=>$payment_page_info[$lang]['p_card_owner'],
                                'card_num'=>$payment_page_info[$lang]['p_card_no'],
                                'card_cvv'=>$payment_page_info[$lang]['p_cvv'],
                                'card_cvv_note'=>$payment_page_info[$lang]['p_cvv_note'],
                                'expiry_date'=>$payment_page_info[$lang]['p_expiry_date'],
                                'agreement'=>$payment_page_info[$lang]['p_agreement'],
                                'agree_c'=>$payment_page_info[$lang]['p_agree_c'],
                                'captcha'=>$payment_page_info[$lang]['p_captcha'],
                                'p_expiry_y'=>$payment_page_info[$lang]['p_expiry_y'],
                                'p_expiry_m'=>$payment_page_info[$lang]['p_expiry_m'],
                                'captcha_note'=>$payment_page_info[$lang]['p_captcha_msg'],
                            );

$ajax_order_ref         = 'orderRef';// : 'orderRefFree';
//hiddens for mobile payment need.
$form['hiddens']        = array(
                                'submit_btn'=>1,
                                'login_id'=>$login_id,
                                'pkgInfo_id'=>$pkgInfo_id,
                                'pkgInfo_version'=>$pkgInfo_version,
                                'item'=>$ajax_order_ref,
                                'p_lang'=>$lang,
                                'pukey'=>$pukey,
                                'is_post_form'=>$is_post_page,
                            );
//other hidden vars.
if (!empty($access_token)) {
    $form['hiddens']['oauth_token'] = $access_token;
}

//buttons.
$form['button']          = array(
                                'cancel'=>array('value'=>$payment_buttons[$lang]['cancel'],'link'=>$cancel_url),
                                'previous'=>array('value'=>$payment_buttons[$lang]['previous'],'link'=>$back_url_top),
                                'submit'=>array('value'=>$payment_buttons[$lang]['confirm'],'link'=>NULL),
                            );

//include thie template for plan cmodel page.
include "..".OAuthModelConfig::DEFAULT_MOBILE_TEMPLATE.OAuthModelConfig::$mobile_teplate_page[$page];

?>
